package bitmap;

import java.util.Arrays;

public class BitMap {
    byte[] elements;
    int usedSize;

    public BitMap(int num) {
        elements = new byte[num / 8 + 1];
    }

    public void insert(int val) {
        if (val < 0) {
            throw new ArrayIndexOutOfBoundsException();
        }
        int byteIndex = val / 8;
        while (byteIndex > elements.length - 1) {
            elements = Arrays.copyOf(elements, elements.length + 1);
        }
        int bitIndex = val % 8;
        elements[byteIndex] |= (1 << bitIndex);
        usedSize++;
    }

    public boolean get(int val) {
        if (val < 0) {
            throw new ArrayIndexOutOfBoundsException();
        }
        int byteIndex = val / 8;
        if (byteIndex > elements.length - 1) {
            System.out.println("坐标越界违法");
            return false;
        }
        int bitIndex = val % 8;
        if (((elements[byteIndex]) & (1 << bitIndex)) != 0) {
            return true;
        }
        return false;
    }

    public void reSet(int val) {
        if (val < 0) {
            throw new ArrayIndexOutOfBoundsException();
        }
        int byteIndex = val / 8;
        if (byteIndex > elements.length - 1) {
            System.out.println("坐标越界违法");
            return;
        }
        int bitIndex = val % 8;
        elements[byteIndex] &= ~(1<<bitIndex);
        usedSize--;
    }
    public int getUsedSize() {
        return usedSize;
    }
}
